package com.example.hello.views;

import com.example.hello.BootstrapButton;
import com.example.hello.ListBox;
import com.example.hello.ListBoxChangeEvent;
import com.example.hello.POJO.POJO;
import com.example.hello.StringWrap;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;

public class Collection extends VerticalLayout implements View {
    
    public final String NAME;

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
    }
    
    public Collection(String NAME) {
        this.NAME = NAME;
    }
    
    public VerticalLayout displayListBox(java.util.Collection<? extends POJO> pojoSet,
                                         final String collection, final StringWrap selectedPOJO,
                                         final boolean append, boolean deletButton) {
        final ListBox pojoList = new ListBox();
        final BootstrapButton view = new BootstrapButton("View");
        view.setSize(BootstrapButton.Size.SMALL);
        view.setWidth("110px");
        final BootstrapButton delete = new BootstrapButton("Delete");
        delete.setSize(BootstrapButton.Size.SMALL);
        delete.setWidth("110px");

        if (!deletButton) {
            view.setWidth("220px");
            delete.setEnabled(false);
        }

        pojoList.setVisibleItems(16);
        for (POJO pojo : pojoSet) pojoList.addItem(pojo.getDecodedName());
        Collections.sort(pojoList.getItems());
        if (pojoList.getItems().size() != 0) {
            selectedPOJO.setString(pojoList.getItems().get(0));
        } else {
            view.setEnabled(false);
            delete.setEnabled(false);
        }
        pojoList.addListener(new Listener() {
            @Override
            public void componentEvent(Event event) {
                if (event instanceof ListBoxChangeEvent) selectedPOJO.setString(((ListBoxChangeEvent) event).getSelected());
            }
        });
        view.addListener(new Listener() {
            @Override
            public void componentEvent(Event event) {
                String location = NAME;
                if (!append) {
                    location = collection + "/" + selectedPOJO.getEncoded();
                } else {
                    location += collection + "/" + selectedPOJO.getEncoded();
                }
                getUI().getNavigator().navigateTo(location);
            }
        });

        return new VerticalLayout(pojoList, new HorizontalLayout(view, delete));
    }

}